package org.phalanx.servlet.webmessages;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.phalanx.logger.SystemLogger;
import org.phalanx.server.PhalanxServer;
import org.phalanx.server.user.PhalanxUser;
import org.phalanx.servlet.websession.ServletAuthenticatorManager;

public class AuthenticationContext implements WebMessageable {
	private PhalanxServer pServer;
	public static final String AUTH_CONTEXT = "authentication";
	public static final String LOGOUT_CONTEXT = "logout";

	public AuthenticationContext(PhalanxServer pServer){
		this.pServer = pServer;
	}
	
	private Cookie createLoggedInCookie(String u){
		Cookie _lUser = new Cookie("_lUser", u);
		_lUser.setMaxAge(60 * 60 * 24 *365);
		_lUser.setPath("/");
		return _lUser;
	}

	@Override
	public void onContextLoadable(String context, Cookie authCookie,
			HttpServletRequest req, HttpServletResponse resp) {
		if (context.equals(AUTH_CONTEXT)){
			try {
				ServletAuthenticatorManager s = new ServletAuthenticatorManager(pServer);
				SystemLogger servletLogger = pServer.getServerLogger();
				PrintWriter p = resp.getWriter();
				Cookie tokenCookie = null;
				boolean cookieAuth = false;

				servletLogger.writeToConsole("Incoming Auth Request", this, SystemLogger.DEBUG);

				resp.setContentType("text/plain");

				String username = (String)req.getParameter("username");
				String password = (String)req.getParameter("password");

				if (authCookie != null && s.authenticate(authCookie) != null){
					cookieAuth = true;
					servletLogger.writeToConsole("Token authentication initiated", this, SystemLogger.DEBUG);
				}
				else {
					tokenCookie = s.authenticate(username, password);
				}

				if (tokenCookie != null || cookieAuth){
					servletLogger.writeToConsole("Login successful", this, SystemLogger.DEBUG);
					if (!cookieAuth){
						resp.addCookie(tokenCookie);
					}
					
					if (cookieAuth){
						PhalanxUser lUser = (PhalanxUser)pServer.getCacheManager().getElement("TokenSessionCache", authCookie.getValue());
						username = lUser.getUserName();
					}
					resp.addCookie(createLoggedInCookie(username));

					p.write("Authentication Success");
				}else {
					p.write("Authentication Failure");
				}
			} catch (IOException ie){
				ie.printStackTrace();
			}
		}
		else if (context.equals(LOGOUT_CONTEXT)){
			try {
				resp.setContentType("text/plain");
				ServletAuthenticatorManager s = new ServletAuthenticatorManager(pServer);
				PrintWriter p = resp.getWriter();
				Cookie sessionCookie = authCookie;
				boolean logoutSuccess = false;

				if (sessionCookie != null){
					logoutSuccess = s.logoutUser(sessionCookie.getValue());
				}

				if (logoutSuccess){
					sessionCookie.setMaxAge(0);
					resp.addCookie(sessionCookie); // Delete cookie
					p.write("Logout OK");
				}
				else {
					p.write("Logout FAIL");
				}
			} catch (IOException ie){
				ie.printStackTrace();
			}
		}
	}

}
